package jwt

import (
	"errors"
	"github.com/dgrijalva/jwt-go"
	"github.com/spf13/viper"
	"time"
)

type CustomClaims struct {
	Id      int
	Type    string
	ExpTime int64
}

func CreateToken(user *CustomClaims) (tokenss string, err error) {
	//自定义claim
	claim := jwt.MapClaims{
		"id":   user.Id,
		"nbf":  time.Now().Unix(),
		"iat":  time.Now().Unix(),
		"exp":  user.ExpTime,
		"type": user.Type,
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
	tokenss, err = token.SignedString([]byte(viper.GetString("token.secret")))
	return
}

func secret() jwt.Keyfunc {
	return func(token *jwt.Token) (interface{}, error) {
		return []byte(viper.GetString("token.secret")), nil
	}
}

func ParseToken(tokenss string) (user *CustomClaims, err error) {
	user = &CustomClaims{}
	token, err := jwt.Parse(tokenss, secret())
	if err != nil {
		return
	}
	claim, ok := token.Claims.(jwt.MapClaims)
	if !ok {
		err = errors.New("cannot convert claim to mapclaim")
		return
	}
	//验证token，如果token被修改过则为false
	if !token.Valid {
		err = errors.New("token is invalid")
		return
	}

	user.Id = int(claim["id"].(float64))
	user.ExpTime = int64(claim["exp"].(float64))
	user.Type = claim["type"].(string)
	return
}
